<template>
  <div class="con">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>登陆</span>
      </div>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login('form')">登陆</el-button>
          <el-button @click="toRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        name: "",
        password: ""
      },
       rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    //登陆
    login(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {
            'user_name':this.form.name,
            'user_psd':this.form.password
          }
          this.$ajax.post('/api/login/',data).then((res) => {
            if (res.status == 1) {
              this.$message(
                  {
                    message: res.message,
                    type: "success"
                  },
                  1000
                );
                localStorage.setItem('userInfo',JSON.stringify(res.data))
                setTimeout(() => {
                  this.$router.push({
                    name: "home"
                  }); 
                }, 1000);
            } else {
              this.$message(
                  {
                    message: res.message,
                    type: "error"
                  },
                  1000
                );
            }
          })
        } else {
          return false;
        }
      });
    },
    toRegister() {
      this.$router.push({
        name: "register"
      });
    }
  }
};
</script>
<style scoped>
.box-card {
  width: 600px;
  margin: 150px auto 0;
}
</style>